/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.scriptutils

import clojure.lang.Compiler
import java.io.Serializable
import java.io.StringReader
import org.slf4j.LoggerFactory
import org.apache.commons.io.IOUtils
import org.apache.oro.text.perl.Perl5Util
import clojure.lang.RT
import org.apache.commons.lang3.Validate

class ClojureScript implements IFigScript, AutoCloseable {
	val static LOG = LoggerFactory.getLogger(ClojureScript)
	var String script
	var String ns;
	new(String path) {
		LOG.info(String.format("加载脚本:%s",path))
		Class.forName("clojure.java.api.Clojure")
		var scriptInput = Thread.currentThread.contextClassLoader.getResourceAsStream(path)
		this.script = IOUtils.toString(scriptInput, "UTF-8")
		Compiler.load(new StringReader(this.script))
		var perl5 = new Perl5Util()
		if (perl5.match("/\\(ns (.*?) .*?\\)/", script)) {
			ns = perl5.group(1)
		}
		Validate.notNull(ns,"未获得ns值")
	}

	override <K, T extends Serializable> K invoke(String name, T value) {
		var foo = RT.^var(ns, name);
		var result = foo.invoke(value);
		return result !== null ? result as K 
	}

	override close() throws Exception {
	}

}
